

package com.ims.common.action.login;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.ims.common.action.BaseAction;
import com.ims.common.email.EMail;
import com.ims.common.email.EmailServices;
import com.ims.common.service.login.LoginService;
import com.ims.common.utils.Constants;
import com.ims.stocks.model.UserLog;
import com.opensymphony.xwork2.ActionContext;





public class LoginAction extends BaseAction implements SessionAware {

    /**
	 * 
	 */
	private static final long serialVersionUID = -7063267975486540449L;
	private String USERNAME;
    private String PASSWORD;
    private String lang;
    private LoginService loginService;
    private String emailid;

    private String mode = "";
	private Map<String, Object> session;

    
    public String execute(){
    	if (PASSWORD == null || PASSWORD.isEmpty() || USERNAME == null || USERNAME.isEmpty()) {
			return INPUT;
		}
			Integer loginAttempt =0;
	    	session.put(Constants.LOGIN_ATTEMPT, loginAttempt);
	    	return SUCCESS;
		
    }
    
    
    

    /**
     * This method returns the values
     * @return the mode
     */
    public String getMode() {
        return mode;
    }


    /**
     * This method sets the value
     * @param mode the mode to set
     */
    public void setMode(String mode) {
        this.mode = mode;
    }

    /**
     * This method returns the values
     *
     * @return the emailid
     */
    public String getEmailid() {
	return emailid;
    }

    /**
     * This method sets the value
     *
     * @param emailid
     *            the emailid to set
     */
    public void setEmailid(String emailid) {
	this.emailid = emailid;
    }

    /**
     * This method returns the values
     *
     * @return the lang
     */
    public String getLang() {
	return lang;
    }

    /**
     * This method sets the value
     *
     * @param lang
     *            the lang to set
     */
    public void setLang(String lang) {
	this.lang = lang;
    }

    /**
     * This method sets the value
     *
     * @param loginService
     *            the loginService to set
     */
    public void setLoginService(LoginService loginService) {
	this.loginService = loginService;
    }

    /**
     * This method returns the values
     *
     * @return the uSERNAME
     */
    public String getUSERNAME() {
	return USERNAME;
    }

    /**
     * This method sets the value
     *
     * @param username
     *            the uSERNAME to set
     */
    public void setUSERNAME(String username) {
	USERNAME = username;
    }

    /**
     * This method returns the values
     *
     * @return the pASSWORD
     */
    public String getPASSWORD() {
	return PASSWORD;
    }

    /**
     * This method sets the value
     *
     * @param password
     *            the pASSWORD to set
     */
    public void setPASSWORD(String password) {
	PASSWORD = password;
    }

    
    public String mailPassword() {
	String output = INPUT;
	if(loginService.chkValidUser(emailid) != null && loginService.chkValidUser(emailid).getStatus() != 2  ) {

	    String password = loginService.txUpdateUserDetails(emailid, 6);
	    String message = generateMailBody(emailid, password);
	    EMail.sendEMail(getConfig("smtp.hostname"), emailid,
			    getConfig("smtp.from.address"),
			    getText("changepwd.mail.subject"),
			    message, getConfig("smtp.cc.address"));
	    addActionMessage(getText("login.forgotpwd.mailack"));
	    output = SUCCESS;
	} else if(loginService.chkValidUser(emailid) != null && loginService.chkValidUser(emailid).getStatus() == 2  ) {
	    saveActionError(getText("login.emailid.locked"));
	}else {
	    saveActionError("common.field.invalid", getText("login.emailid"));

	}
	return output;

    }

    /**
	  * This method create the body for the mail
	  */
	public String generateMailBody(String emailId, String password) {
	    String emailBodyString = null;
		try {
		    UserLog userInfo = loginService.loadUserInfo(emailId);
		    EmailServices emailServices=new EmailServices();
		    HashMap<String, Object> emailParamMap = new HashMap<String, Object>();
		    emailParamMap.put("EMAIL_ID", emailId);
		    emailParamMap.put("EMP_NAME", userInfo.getUserDetails().getEmployee().getPerson().getFirstName()+ " " + userInfo.getUserDetails().getEmployee().getPerson().getLastName());
		    emailParamMap.put("NEW_PASSWORD", password);
		    emailParamMap.put("CONTACT_ADDR", getConfig("email.template.contact"));
		    emailParamMap.put("FROM_REGARDS", getConfig("email.template.regards.name"));
		    emailParamMap.put("URL_APPLICATION", getConfig("website.path"));
		    emailBodyString = emailServices.createEmailUsingTemplate(
				    "resetpassword.ftl", emailParamMap);

		} catch(Exception ex) {
		    LOG.error("error occured while creation of template" + ex.getMessage());
		}
		return emailBodyString;

	}

    /*
     * (non-Javadoc)
     * @see com.opensymphony.xwork2.ActionSupport#validate()
     */
    @Override
    public void validate() {

	if(mode != null & "save".equalsIgnoreCase(mode)) {
	    if(emailid == null || emailid.length() == 0) {

		saveActionError("common.field.required",
				getText("login.emailid"));
		setErrorID("emailid");
	    }
	}
	return;
    }

    public String logout() {
	ActionContext.getContext().getSession().clear();
	ActionContext.getContext().getSession().put("USER_SESSSION_HANDLE", null);


	HttpServletRequest req = ServletActionContext.getRequest();

	Enumeration<?> en = req.getSession().getAttributeNames();
		while(en.hasMoreElements()){
		    String name = String.valueOf(en.nextElement());
		    req.getSession().removeAttribute(name);

		}

	if(req.getSession() != null) {
	    req.getSession().invalidate();

	}

	return "login";
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ActionSupport#input()
     */
    @Override
    public String input() throws Exception {
	setTitle(getText("forgotpassword.title"));
        return super.input();
    }


	public LoginService getLoginService() {
		return loginService;
	}




	@Override
	public void setSession(Map<String, Object> session) {
			this.session=session;
	}







	

}
